import React from 'react';
import { Message, Space, Typography, Upload } from '@arco-design/web-react';
import { UploadItem, UploadProps } from '@arco-design/web-react/es/Upload';
import { uploadFile } from '@/services/merchant';
import styles from './index.module.less';

export function SSSUpload(
  props: {
    desc?: string | React.ReactNode;
    value?: UploadItem[];
    onChange?: (value: any) => void;
  } & UploadProps
) {
  const { desc, value, onChange, ...rest } = props;

  return (
    <Space className={styles.container}>
      <Upload
        accept={{ type: 'image/*' }}
        limit={1}
        imagePreview
        listType="picture-card"
        fileList={value}
        onChange={onChange}
        customRequest={(option) => {
          const { onProgress, onError, onSuccess, file } = option;
          const formData = new FormData();
          formData.append('file', file);
          uploadFile(formData, (event) => {
            if (event.total > 0) {
              event.percent = (event.loaded / event.total) * 100;
            }
            onProgress(event);
          })
            .then((response) => {
              onSuccess(response);
              Message.success('上传成功');
            })
            .catch((error) => {
              onError(error);
              Message.error('上传失败');
            });
        }}
        {...rest}
      ></Upload>

      {typeof desc === 'string' ? (
        <Typography.Text
          type="secondary"
          style={{ fontSize: 12, color: 'var(--color-text-3)' }}
        >
          {desc}
        </Typography.Text>
      ) : (
        desc
      )}
    </Space>
  );
}
